package com.googlecode.pacswitch;

import java.util.ArrayList;
import java.util.List;

import javax.xml.bind.JAXBElement;
import javax.xml.bind.annotation.XmlAnyElement;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlTransient;
import javax.xml.bind.annotation.XmlType;

/**
 * @author Andrey Pavlenko
 */
@XmlType(name = "Rule", namespace = ObjectFactory.NS)
public class Rule {
    private PString _name;
    private final List<JAXBElement<?>> _nestedElements = new ArrayList<>(2);

    @XmlAnyElement(lax = true)
    public List<JAXBElement<?>> getNestedElements() {
        return _nestedElements;
    }

    @XmlAttribute(required = true)
    public PString getName() {
        return _name;
    }

    public void setName(final PString name) {
        _name = name;
    }

    @XmlTransient
    public Condition getCondition() {
        for (final JAXBElement<?> e : _nestedElements) {
            final Object v = e.getValue();

            if (v instanceof Condition) {
                return (Condition) v;
            }
        }

        return Condition.TRUE;
    }

    @XmlTransient
    public Action getAction() {
        for (final JAXBElement<?> e : _nestedElements) {
            final Object v = e.getValue();

            if (v instanceof Action) {
                return (Action) v;
            }
        }

        throw new IllegalStateException("Missing action in rule " + getName());
    }
}
